//
//  QiNiuApiManager.m
//  PetExchange
//
//  Created by a on 2021/2/26.
//

#import "QiNiuApiManager.h"

@implementation QiNiuApiManager
+(QiNiuApiManager *)shareManager{
    static QiNiuApiManager *sharedGlobalInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedGlobalInstance = [[self alloc] init];
    });
    return sharedGlobalInstance;
}

-(id)init{
    self=[super init];
    if (self) {
        self.upManager = [[QNUploadManager alloc] init];
        self.qiniuServerUrl = @"http://cdn.lesuyipay.com/";
        //        if ((MySafeString(self.upToken)).length < 1) {
        //            [self getQiNiuToken];
        //        }
    }
    return self;
}

- (void)getQiNiuToken {
    //这里写七牛获取token 的数据请求  成功后，用block 回调
    [[HttpHelper sharedInstance] sendGet:@"qiniu/getToken" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            NSDictionary *dict = responseObject.data[@"data"];
            self.upToken = MySafeString(dict[@"qiniuToken"]);
            self.qiniuServerUrl = dict[@"qiniuUrl"];
            if (self.getTokenSuccessBlock) {
                self.getTokenSuccessBlock();
            }
        }
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}



- (void)uploadWithFilePath:(NSString *)filePath andUpKey:(NSString *)key andUpFail:(void (^)(QNResponseInfo *))failInfo andUpSuccess:(void(^)(NSDictionary *infoDict))upFinsh andUpLoadProgress:(void(^)(float progress))upProgress {
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        if (upProgress) {
            upProgress(percent);
        }
        if (percent >= 1){
         
            NSLog(@"上传成功");
        }
        
    }params:nil checkCrc:NO cancellationSignal:nil];
    [self.upManager putFile:filePath key:key token:self.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if(info.statusCode == 200){
            if (upFinsh) {
                upFinsh(resp);
            }
        }else {
            if(failInfo){
                failInfo(info);
            }
        }
    } option:uploadOption];
}


- (void)upLoadPHAsset:(PHAsset *)phAsset andUpKey:(NSString *)key andUpFail:(void (^)(QNResponseInfo *))failInfo andUpSuccess:(void(^)(NSDictionary *infoDict))upFinsh andUpLoadProgress:(void(^)(float progress))upProgress {
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        if (upProgress) {
            upProgress(percent);
        }
        if (percent >= 1){
            NSLog(@"上传成功");
        }
        
    }params:nil checkCrc:NO cancellationSignal:nil];
    
    [self.upManager  putPHAsset:phAsset key:key token:self.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        if(info.statusCode == 200){
            if (upFinsh) {
                upFinsh(resp);
            }
        }else {
            if(failInfo){
                failInfo(info);
            }
        }
    } option:uploadOption];
    
}


- (void)upLoadImageWithUploadKey:(NSString *)key andImage:(UIImage *)upImage andFinshInfo:(void(^)(NSDictionary *infoDict))upFinsh andUpFail:(void (^)(QNResponseInfo * fail))failInfo andUpLoadProgress:(void(^)(float progress))upProgress;{
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        NSLog(@"percent == %.2f", percent);
        if (upProgress) {
            upProgress(percent);
        }
    } params:nil checkCrc:NO cancellationSignal:nil];
    NSData *data;
    
    UIImage *finallImage =  [self compressImageSize:upImage toByte:1024*1024*3.0];
    data = UIImageJPEGRepresentation(finallImage,0.5);
    
//    if (UIImagePNGRepresentation(upImage) == nil) {
//        data = UIImageJPEGRepresentation(upImage, 0.6);
//    } else {
//        data = UIImagePNGRepresentation(upImage);
//    }
    [self.upManager putData:data key:key token:self.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSLog(@"info ===== %@", info);
        NSLog(@"resp ===== %@", resp);
        if(info.statusCode == 200){
            if (upFinsh) {
                upFinsh(resp);
            }
        }else {
            if(failInfo){
                failInfo(info);
            }
        }
    } option:uploadOption];
    
}

- (NSData *)compressQualityWithMaxLength:(NSInteger)maxLength andImage:(UIImage *)image {
    CGFloat compression = 1;
    maxLength = 1.5*1024*1024;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    if (data.length < maxLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(self, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}


+ (NSString *)getImageKeyWithType:(NSString *)tpye {
    NSString *num = @"";
    NSString *name = [NSString stringWithFormat:@"%@%@",[Helper getCurrentTimes],num];
    //设置上传key
    NSString *upKey = [NSString stringWithFormat:@"%@_%@%@.png",tpye,@"image",name];
    return upKey;
}


+ (NSString *)getVideoKey {
    NSString *num = @"";
    NSString *name = [NSString stringWithFormat:@"%@%@",[Helper getCurrentTimes],num];
    //设置上传key
    NSString *upKey = [NSString stringWithFormat:@"%@%@",@"Video",name];
    return upKey;
}

+ (NSString *)getVoiceKey {
    NSString *num = [NSString stringWithFormat:@"%.4d", (arc4random() % 10000)];
    NSString *name = [NSString stringWithFormat:@"%@%@",[Helper getCurrentTimes],num];
    //设置上传key
    NSString *upKey = [NSString stringWithFormat:@"%@%@",@"voice",name];
    return upKey;
}

#pragma mark - 图片压缩
/*!
 *  @brief 使图片压缩后刚好小于指定大小
 *
 *  @param image 当前要压缩的图 maxLength 压缩后的大小
 *
 *  @return 图片对象
 */
//图片质量压缩到某一范围内，如果后面用到多，可以抽成分类或者工具类,这里压缩递减比二分的运行时间长，二分可以限制下限。
- (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}



@end
